const handleRoute = require('./src/routes/handleRoute');

// 处理POST数据
const getPostData = (req) => {
    const promise = new Promise((resolve, reject) => {
        if (req.method !== 'POST') {
            resolve({});
            return;
        }

        if (req.headers['content-type'] !== 'application/json') {
            resolve({});
            return;
        }

        // 获取POST数据
        let postData = '';
        req.on('data', (chunk) => {
            postData += chunk.toString();
        });

        req.on('end', () => {
            if (!postData) {
                resolve({});
                return;
            }
            resolve(JSON.parse(postData));
        });
    });

    return promise;
}


const serverHandler = (req, res) => {
    // 设置响应头
    res.setHeader('Content-Type', 'application/json');
    // 获取请求地址
    const url = req.url;
    req.path = url.split('?')[0];

    // 解析请求参数
    req.query = require('querystring').parse(url.split('?')[1]);

    // 处理post数据
    getPostData(req).then((postData) => {
        req.body = postData;
        // 处理路由
        const DataPeomise = handleRoute(req, res);
        // 判断是否有返回数据
        if (DataPeomise) {
            DataPeomise.then((Data) => {
                res.end(JSON.stringify(Data));
            });
            return;
        }
        // 如果没有返回数据，则返回404
        res.statusCode = 404;
        res.end('404 Not Found');

    });
};

module.exports = serverHandler;